/**
 * @author yxw
 * date : 2013年9月30日 下午3:43:33 
 */
package com.tzinfo.tzt.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.view.ImageAdapter;
import com.tzinfo.tzt.activity.view.XListView;
import com.tzinfo.tzt.activity.view.XListView.IXListViewListener;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.config.FilterConfig;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.OldhouseList;
import com.tzinfo.tzt.service.HouseHistoryService;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

public class FilterOldHouseResultActivity extends BaseActivity implements
		IXListViewListener, OnClickListener, OnItemClickListener {

	private Button btnBack;
	private LinearLayout layoutConstraint;
	private TextView titleText, constraintText;

	private XListView xListView;

	private List<Map<String, Object>> data;
	private List<Object> houseList;
	private Handler mHandler;
	// 筛选相关
	private int[] filterResult;
	private StringBuilder filterStr = new StringBuilder("?listtype=1");
	private String baseUrl = AppDataConfig.oldUrl
			+ AppDataConfig.OldhouseList;


	private ImageAdapter imageAdapter;


	private MyResultList oldHouseListResult;
	private HouseHistoryService historyService;

	static String sID = "sID";
	static String sStyle = "Style";
	static String sLogo = "Logo";
	static String sName = "Name";
	static String sAddress = "Address";
	static String sSize = "Size";
	static String sPrice = "Price";
	private int pageNum = 1;
	private static final int pageSize = 10;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_filter_house);
		historyService=new HouseHistoryService(this);
		createfilterStr();
		init();
		showProgressBar();
		new Thread(getOldHouseListResultRun).start();
	}

	private void createfilterStr() {
		Intent thisIntent = this.getIntent();
		filterResult = thisIntent.getIntArrayExtra("filterResult");
		filterStr.append("&areaid=" + filterResult[0]);
		String price = FilterConfig.FILTER_PRICE_W[filterResult[2]];
		if (filterResult[2] == 0) {
			// filterStr.append("&money= ");
		} else if (filterResult[2] == FilterConfig.FILTER_PRICE_W.length-1) {
			price = price.substring(0, price.length() - 4)+"-";
			filterStr.append("&money=" + price);
		} else {
			price = price.substring(0, price.length() - 2);
			filterStr.append("&money=" + price);
		}
		
		String room = filterResult[4]+"";
		filterStr.append("&room=" + room);
		
		String size=FilterConfig.FILTER_SIZE[filterResult[5]];
		if(filterResult[5]==FilterConfig.FILTER_SIZE.length-1){
			size=size.substring(0, size.length()-4)+"-";
			filterStr.append("&size=" + size);
		}else if(filterResult[5]!=0){
			size=size.substring(0, size.length()-2);
			filterStr.append("&size=" + size);
		}
		
		String type=filterResult[6]+"";
		if(filterResult[6]!=0){
			filterStr.append("&type=" + type);
		}
		
	}

	private void init() {
		mHandler = new Handler();
		mProgressBar = (ProgressBar)findViewById(R.id.progressbar_loding);
		xListView = (XListView) findViewById(R.id.xListView_local);
		xListView.setPullRefreshEnable(false);
		xListView.setPullLoadEnable(true);
		// xListView.setPullLoadEnable(false);
		// xListView.setPullRefreshEnable(false);
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(this);
		constraintText = (TextView) this.findViewById(R.id.text_constraint);
		String t = "找房条件：";
		for (int i = 0; i < filterResult.length; i++) {
			if (filterResult[i] != 0) {
				t += FilterConfig.FILTER_CONTENT[i][filterResult[i]] + " | ";
			}
		}
		if(t.length()!=5){
			t=t.substring(0, t.length()-3);
		}else{
			t="您没有设置找房条件";
		}
		constraintText.setText(t);
		titleText = (TextView) this.findViewById(R.id.text_title);
		titleText.setText("二手房");

		btnBack = (Button) this.findViewById(R.id.bt_back);
		btnBack.setOnClickListener(this);
		layoutConstraint = (LinearLayout) this
				.findViewById(R.id.layout_constraint);
		layoutConstraint.setOnClickListener(this);
	}

	private void newAdapter() {
		// 自定义的图片适配器
		imageAdapter = new ImageAdapter(this, data, R.layout.item_main_list,
				new String[] { sLogo, sName, sAddress, sSize, sPrice, sID },
				new int[] { R.id.list_item_image, R.id.list_item_title,
						R.id.list_item_address, R.id.list_item_size,
						R.id.list_item_price, R.id.un_house_id });
	}

	private void updateUI() {
		newAdapter();
		// xListView.setAdapter(simpleAdapter);
		xListView.setAdapter(imageAdapter);
	}

	/**
	 * 将得到的数据装载进ArrayList<Map<String, Object>>() data中
	 */
	private void getData() {
		data = new ArrayList<Map<String, Object>>();
		OldhouseList oldListItem;
		Map<String, Object> map;
		if (oldHouseListResult.getSuccess()) {
			houseList=oldHouseListResult.getData();
			for (int i = 0; i < oldHouseListResult.getData().size(); i++) {
				oldListItem = (OldhouseList) oldHouseListResult.getData()
						.get(i);
				map = new HashMap<String, Object>();
				map.put(sLogo, oldListItem.getLogo());
				String strName = oldListItem.getName();
				if (strName.length() > 9) {
					strName = strName.substring(0, 9) + "…";
				}
				map.put(sName, strName);
				String strAddress = oldListItem.getAddress();
				if (strAddress.length() > 20) {
					strAddress = strAddress.substring(0, 20) + "…";
				}
				map.put(sAddress, strAddress);
				map.put(sSize,
						oldListItem.getStyle() + " " + oldListItem.getSize()
								+ "平米");
				String price = oldListItem.getPrice();
				if ("0万".equals(price)) {
					price = "售价待定";
				}
				map.put(sPrice, price);
				map.put(sID, oldListItem.getID());
				data.add(map);
			}
		}
	}

	private void getMoreData() {
		OldhouseList oldListItem;
		Map<String, Object> map;
		if (oldHouseListResult.getSuccess()) {

			for (int i = 0; i < oldHouseListResult.getData().size(); i++) {
				houseList.add(oldHouseListResult.getData().get(i));
				oldListItem = (OldhouseList) oldHouseListResult.getData()
						.get(i);
				map = new HashMap<String, Object>();
				map.put(sLogo, oldListItem.getLogo());
				String strName = oldListItem.getName();
				if (strName.length() > 8) {
					strName = strName.substring(0, 9) + "…";
				}
				map.put(sName, strName);
				String strAddress = oldListItem.getAddress();
				if (strAddress.length() > 20) {
					strAddress = strAddress.substring(0, 20) + "…";
				}
				map.put(sAddress, strAddress);
				map.put(sSize,
						oldListItem.getStyle() + "  " + oldListItem.getSize()
								+ "平米");
				String price = oldListItem.getPrice();
				if ("0万".equals(price)) {
					price = "售价待定";
				}
				map.put(sPrice, price);
				map.put(sID, oldListItem.getID());
				data.add(map);
			}
		}
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						showProgressBar();
						new Thread(getMoreOldHouseListResultRun).start();
					}
				}).show();
	}

	protected void showLastRow() {
		Toast.makeText(this, "已经是最后一页！", 5000).show();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				getDataError((String) msg.obj);
				break;
			case 1:
				updateUI();
				if (xListView.getFooterViewsCount() == 0) {
					xListView.addFooterView(xListView.getmFooterView());
				}
				removeProgressBar();
				onLoad();
				break;
			case 2:
				if (xListView.getFooterViewsCount() == 0) {
					xListView.addFooterView(xListView.getmFooterView());
				}
				imageAdapter.notifyDataSetChanged();
				onLoad();
				break;
			case 3:
				// 最后一页
				showLastRow();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				onLoad();
				break;
			case 4:
				// 没有数据
				updateUI();
				data.clear();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				imageAdapter.notifyDataSetChanged();
				// xListView.setVisibility(View.GONE);
				removeProgressBar();
				onLoad();
				break;
			case 5:
				// 只有一页
				updateUI();
				onLoad();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				removeProgressBar();
				break;
			case 0:
				break;
			}
		}
	};

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		xListView.setRefreshTime(df.format(new Date()));
	}

	private void initData() {
		pageNum = 1;
		// 通过线程访问网络得到数据
		new Thread(getOldHouseListResultRun).start();
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				// getData();
				// 如果刷新后数据不变，会出错
				// simpleAdapter.notifyDataSetChanged();
				// newAdapter();
				// xListView.setAdapter(simpleAdapter);
				pageNum = 1;
				initData();

			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				pageNum++;
				new Thread(getMoreOldHouseListResultRun).start();

			}
		}, 2000);
	}

	/**
	 * 线程 得到新房列表
	 */
	Runnable getOldHouseListResultRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String sFilter = filterStr.toString() + "&pagenumber=" + pageNum
					+ "&pagesize=" + pageSize;
			Log.wtf("url", baseUrl + sFilter);
			jsonString = HttpTools.getJsonContent(baseUrl + sFilter);
			Log.e("JsonString", jsonString);
			oldHouseListResult = JsonTools.getOldhouseList(jsonString);
			getData();
			if (oldHouseListResult.getSuccess()) {
				if (oldHouseListResult.getData().size() == 0) {
					msg.arg1 = 4;
				} else if (oldHouseListResult.getData().size() < pageSize) {
					msg.arg1 = 5;
				} else {
					msg.arg1 = 1;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = oldHouseListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};
	/**
	 * 线程 得到新房列表
	 */
	Runnable getMoreOldHouseListResultRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String sFilter = filterStr.toString() + "&pagenumber=" + pageNum
					+ "&pagesize=" + pageSize;
			jsonString = HttpTools.getJsonContent(baseUrl + sFilter);
			Log.e("JsonString", jsonString);
			oldHouseListResult = JsonTools.getOldhouseList(jsonString);
			getMoreData();
			if (oldHouseListResult.getSuccess()) {
				if (oldHouseListResult.getData().size() == 0) {
					msg.arg1 = 3;
				} else {
					msg.arg1 = 2;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = oldHouseListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			finish();
			break;
		case R.id.layout_constraint:
			// 跳转到定位条件选择页面
			this.finish();
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(FilterOldHouseResultActivity.this,
				OldHouseDetailActivity.class);
		OldhouseList item= (OldhouseList) houseList.get((int) arg3);
		TextView text = (TextView) arg1.findViewById(R.id.un_house_id);
		intent.putExtra("houseId", text.getText().toString());
		intent.putExtra("oldhouseList", item);
		historyService.saveOldHouse(item);
		startActivity(intent);
	}

}
